package br.com.quiz.converter;

import java.awt.Dimension;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

import br.com.quiz.domain.Disciplina;

@FacesConverter( value = "primeFacesPickListConverter" )
public class ConverterPickList implements Converter{

//	@Override
//	public Object getAsObject( FacesContext arg0, UIComponent arg1, String arg2 ) {
//		Object ret = null;
//		if ( arg1 instanceof PickList ) {
//			Object dualList = ( (PickList) arg1 ).getValue();
//			DualListModel dl = (DualListModel) dualList;
//			for ( Iterator iterator = dl.getSource().iterator(); iterator.hasNext(); ) {
//				Object o = iterator.next();
//				String id = ( new StringBuilder() ).append( ( (AbstractBean) o ).getId() ).toString();
//				if ( arg2.equals( id ) ) {
//					ret = o;
//					break;
//				}
//
//			}
//
//			if ( ret == null ) {
//				for ( Iterator iterator1 = dl.getTarget().iterator(); iterator1.hasNext(); ) {
//					Object o = iterator1.next();
//					String id = ( new StringBuilder() ).append( ( (AbstractBean) o ).getId() ).toString();
//					if ( arg2.equals( id ) ) {
//						ret = o;
//						break;
//					}
//				}
//			}
//
//		}
//		return ret;
//	}
//
//	@Override
//	public String getAsString( FacesContext arg0, UIComponent arg1, Object arg2 ) {
//		String str = "";
//		if ( arg2 instanceof AbstractBean )
//			str = ( (AbstractBean) arg2 ).getId().toString();
//		return str;
//
//	}
//	@Override
//	public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s)     {
//	    @SuppressWarnings("unchecked")
//	    DualListModel<Disciplina> value = (DualListModel<Disciplina>) ((PickList) uiComponent).getValue();
//	    List<Disciplina> source = value.getSource();
//	    for (Disciplina d : source) {
//	        if(s.equals(d)){
//	            return d;
//	        }
//	    }
//
//	    return null;
//	}
//
//	@Override
//	public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
//	    return ((Disciplina)o).toString();
//	}
	
    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
        PickList  p = (PickList) component;
        DualListModel dl = (DualListModel) p.getValue();
        return dl.getSource().get(Integer.valueOf(submittedValue));
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        PickList  p = (PickList) component;
        DualListModel dl = (DualListModel) p.getValue();
        return  String.valueOf(dl.getSource().indexOf(value));
    }

}